local S = kiosk.intllib
local F = minetest.formspec_escape

minetest.register_on_player_receive_fields(function(player, formname, fields)
-- check received fields for items handled by kiosk function
--	print(dump2(fields))
	local ui_current_page=unified_inventory.current_page[player:get_player_name()]
	if ui_current_page ~= nil then
		if ui_current_page == kiosk.prefix then
			for i,v in pairs(fields) do
				if i == "kiosk_button_sell" then
				-- Sell button is pressed and items in sell field are converted into account
					kiosk.player_sell(player)
					unified_inventory.set_inventory_formspec(player, "kiosk")
				end
				if string.sub(i, 1, 21) == "item_button_nochange_" then
				-- Item in preview is pressed. One item is placed into buy field and price is shown
					local buy_item=kiosk.demangle_for_formspec(i:sub(22))
--					print(dump2(buy_item))
					local buy_price=kiosk.get_buy(buy_item)
					print(buy_item.." @ "..buy_price)
					local playername=player:get_player_name()
					-- place one item
					local player_inv=minetest.get_inventory({type="detached",name=playername.."_buy"})
					player_inv:set_stack("main",1,{name=buy_item,count=1})
					-- update formspec
					unified_inventory.set_inventory_formspec(player, "kiosk")
					return player,formname,{}
				end
			end
		end
	end
end)

minetest.register_on_joinplayer(function(player)
-- create detached inventories for selling and bying
	local playername=player:get_player_name()
	if playername == nil then return end
	if playername == "" then return end
	
	-- sell inventory with on_put function. If item is placed here the price is printed into formspec
	local sell = minetest.create_detached_inventory(playername.."_sell",{
		on_put = function(inv, listname, index, stack, player)
			local item_stack=inv:get_stack(listname,index)
			if item_stack == nil then return end
			local item_name=item_stack:get_name()
			if item_name == nil then return end
			local item_count=item_stack:get_count()
			if item_count <1 then return end
			local price = kiosk.get_sell(item_name)
			print("Would buy "..item_name.." @ "..price..". For "..item_count.." you get "..(item_count*price)..".")
			local player_name = player:get_player_name()
			unified_inventory.set_inventory_formspec(player, "kiosk")
		end,
		})
	sell:set_size("main", 1)
	
	-- buy inventory
	local buy = minetest.create_detached_inventory(playername.."_buy", {
		on_put = function(inv, listname, index, stack, player)
			local player_name = player:get_player_name()
		end,
		allow_put = function(inv, listname, index, stack, player)
		  -- not allowing putting items in this field. Doesn't make sense
			return 0
		end,
		allow_take = function(inv, listname, index, stack, player)
		  -- check, if account has enough money for taking itemstack
			local item_stack=inv:get_stack(listname,index)
			if item_stack == nil then return 0 end
			local item_name=item_stack:get_name()
			if item_name == nil then return 0 end
			local item_count=item_stack:get_count()
			if item_count <1 then return 0 end
			local price = kiosk.get_buy(item_name)
			local player_balance=xpfw.player_get_attribute(player,kiosk.account)
			local max_allowed= (-1)
			if player_balance <= price then
				max_allowed= 0
			end
			return max_allowed
		end,
		on_take = function(inv, listname, index, stack, player)
			-- take items from detached inventory
			local item_stack=inv:get_stack(listname,index)
			if item_stack == nil then return end
			local item_name=item_stack:get_name()
			if item_name == nil then return end
			local item_count=item_stack:get_count()
			if item_count <1 then return end
			local price = kiosk.get_buy(item_name) * item_count
			-- calc price and substract from account
			xpfw.player_sub_attribute(player,kiosk.account,price)
			xpfw.player_add_attribute(player,"kiosk_bought",item_count)
			-- reset detached inventory
			local player_inv=minetest.get_inventory({type="detached",name=player:get_player_name().."_buy"})
			player_inv:set_stack("main",1,{name=item_name,count=1})
			
			
			local kinv=kiosk.inventar[item_name]
			kinv.stock=kinv.stock-item_count
			unified_inventory.set_inventory_formspec(player, "kiosk")
		end,
	})
	buy:set_size("main", 1)
	local pdef={name=playername,
		sell=sell,
		buy=buy,}
	kiosk.player[playername]=pdef
end)

-- register xpfw attribute
xpfw.register_attribute(kiosk.account,{min=0,max=math.huge,default=0,
	hud=1,})
xpfw.register_attribute("kiosk_sold",{min=0,max=math.huge,default=0,
	hud=1,})
xpfw.register_attribute("kiosk_bought",{min=0,max=math.huge,default=0,
	hud=1,})


-- ui button for formspec
unified_inventory.register_button("kiosk", {
	type = "image",
	image = "kiosk_button_128.png",
	tooltip = S("Kiosk")
})


-- ui formspec definition
unified_inventory.register_page(kiosk.prefix, {
	get_formspec = function(player, perplayer_formspec)
		local fy = perplayer_formspec.formspec_y
		local name = player:get_player_name()
		local player_inv=minetest.get_inventory({type="detached",name=name.."_sell"})
		local sellprice=""
		-- check sell field
		if player_inv ~= nil then
			local sell_stack=player_inv:get_stack("main",1)
			if sell_stack ~= nil then 
				local sell_count = sell_stack:get_count()
				if sell_count >= 1 then
					sellprice=sellprice.." "..sell_count.."x"
				end
				local sell_item=sell_stack:get_name()
				if sell_item ~= nil then 
					if sell_item ~= "" then
						sellprice=sellprice.." "..sell_item
					end
				end
				local price_single = kiosk.get_sell(sell_item)
				local price=price_single * sell_count
				sellprice=sellprice.." @ "..price
			end
		end
		-- check buy field
		local player_buy=minetest.get_inventory({type="detached",name=name.."_buy"})
		local buyprice=""
		if player_buy ~= nil then
			local buy_stack=player_buy:get_stack("main",1)
			if buy_stack ~= nil then 
				local buy_count = 1
				if buy_count >= 1 then
					buyprice=buyprice.." "..buy_count.."x"
				end
				local buy_item=buy_stack:get_name()
				if buy_item ~= nil then 
					if buy_item ~= "" then
						buyprice=buyprice.." "..buy_item
					end
				end
				local price_single = kiosk.get_buy(buy_item)
				local price=price_single * buy_count
				buyprice=buyprice.." @ "..price
			end
		end
		-- check account balance
		local kiosk_balance=math.ceil(xpfw.player_get_attribute(player,kiosk.account)*100)/100
		-- generate formspec
		local formspec = "label[0,0;"..F(S("Kiosk")).."]"..
			"list[detached:"..name.."_sell;main;1,1;1,1;]"..
			"list[detached:"..name.."_buy;main;1,2;1,1;]"..
			"button[2,1;2,1;kiosk_button_sell;"..S("Sell").."]"..
			"button[2,2;2,1;kiosk_button_buy;"..S("Buy").."]"..
			"label[4.0,1;"..F(sellprice).."]"..
			"label[4.0,2;"..F(buyprice).."]"..
			"label[2.0,3;"..F(S("Balance")..": "..kiosk_balance).."]"..
			"listring[current_player;main]"..
			"listring[detached:"..name.."_kiosk;kiosk]"
		return {formspec=formspec}
	end,
})

minetest.after(1,function()
end)


local mn_compare=function(a,b)
	return kiosk.map_stat[a]>kiosk.map_stat[b]
end

minetest.register_on_generated(function(minp,maxp,seed)
	local gen_vol=1
	for _,i in ipairs({"x","y","z"}) do
		kiosk.map_extend.emin[i]=math.min(kiosk.map_extend.emin[i],minp[i])
		kiosk.map_extend.emax[i]=math.max(kiosk.map_extend.emax[i],maxp[i])
		gen_vol=gen_vol*(maxp[i]-minp[i]+1)
	end
	kiosk.map_extend.volume=kiosk.map_extend.volume+gen_vol
	print(dump2(kiosk.map_extend))
	
end)

